package com.android.example.record.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.RecyclerView;

import com.android.example.record.R;
import com.android.example.record.activity.QueryRecordActivity;
import com.android.example.record.bean.RecordBean;
import com.android.example.record.databinding.RecordItemBinding;
import com.android.example.record.utils.Utils;
import com.android.example.record.viewmodel.RecordIDViewModel;
import com.bumptech.glide.Glide;

import java.util.List;

public class RecordAdapter extends RecyclerView.Adapter<RecordAdapter.ViewHolder> {

    private final List<RecordBean> recordBeanList;
    Context context;
    final QueryRecordActivity queryRecordActivity;

    public static class ViewHolder extends RecyclerView.ViewHolder {

        private final RecordItemBinding binding;

        public ViewHolder(@NonNull RecordItemBinding itemBinding) {
            super(itemBinding.getRoot());
            binding = itemBinding;
        }
    }

    public RecordAdapter(List<RecordBean> recordBeanList, QueryRecordActivity queryRecordActivity) {
        this.recordBeanList = recordBeanList;
        this.queryRecordActivity = queryRecordActivity;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        if (context == null) {
            context = parent.getContext();
        }

        RecordItemBinding binding = RecordItemBinding.inflate(LayoutInflater.from(context), parent, false);
        ViewHolder holder = new ViewHolder(binding);
        holder.binding.getRoot().setOnClickListener(v -> {
            int position = holder.getBindingAdapterPosition();
            RecordBean recordBean = recordBeanList.get(position);

            queryRecordActivity.hideSelf();
            RecordIDViewModel viewModel = new ViewModelProvider(queryRecordActivity).get(RecordIDViewModel.class);
            viewModel.getRecordID().setValue(recordBean.getId());
        });

        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        RecordBean recordBean = recordBeanList.get(position);
        holder.binding.siren.setText(recordBean.getSiren());
        holder.binding.number.setText(recordBean.getNumber());
        holder.binding.recordName.setText(recordBean.getRecord_name());
        Glide.with(context).load(Utils.getRecordPath(context) + recordBean.getRecord_name()).into(holder.binding.preview);
        holder.binding.play.setAlpha(0.6f);
        Glide.with(context).load(R.drawable.play).into(holder.binding.play);
    }

    @Override
    public int getItemCount() {
        return recordBeanList.size();
    }
}
